package modelo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;
import controlador.Jugador;

public class XML_DAO {
	public static final String TAG = "TratamientoXML";
	
	public void escribirXML(Activity ma, Jugador j) throws IllegalArgumentException, IllegalStateException, IOException {
		
		ArrayList<String>	supletorio=leerXML(ma);
	  FileOutputStream fout = null;
	  XmlSerializer serializer = Xml.newSerializer();
	   try {
	      fout = ma.openFileOutput("XML_datos.xml", Context.MODE_PRIVATE);
	   } catch (FileNotFoundException e) {
	      Toast.makeText(ma, e.getMessage(), Toast.LENGTH_LONG).show();
	   }
	   
	   	try {
	   	
	   	   serializer.setOutput(fout, "UTF-8");
	   	  serializer.startDocument(null, true);
	   	   serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
	   	} catch (Exception e) {
	   	   Toast.makeText(ma, e.getMessage(), Toast.LENGTH_LONG).show();
	   	}
	 	serializer.startTag(null, "punt");
	 	
	 	
	 
	 
	 
	 for(int i=0;i<supletorio.size();i++){
	   	serializer.startTag(null, "puntuaciones");
	

	   	
	   	
	   	serializer.text(supletorio.get(i));
	   	
	   	serializer.endTag(null, "puntuaciones");
	 }
   	serializer.startTag(null, "puntuaciones");
	

	   	
	   	
	   	serializer.text(j.getNombre()+"    "+j.getVictorias());
	   	
	   	serializer.endTag(null, "puntuaciones");
	   	serializer.endTag(null, "punt");

	   	serializer.endDocument();
	   	serializer.flush();
	   	fout.close();

	  
	   }
	public ArrayList<String> leerXML(Activity ma) {
		FileInputStream fin = null;
		ArrayList<String> jugadores= new ArrayList<String>();
		try {
			fin = ma.openFileInput("XML_datos.xml");
		} catch (Exception e) {
			//Toast.makeText(ma,"hola", Toast.LENGTH_LONG).show();
		}

		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(fin, "UTF-8");
			
			int event = parser.next();
			while(event != XmlPullParser.END_DOCUMENT) {
			
				
				Toast.makeText(ma, "Entrando al if", Toast.LENGTH_LONG).show();
				if(event == XmlPullParser.TEXT && parser.getText().trim().length() != 0){
					
						
						jugadores.add(parser.getText());
						
					
					
				
				}
		

				event = parser.next();
				
			}
			fin.close();

			
		} catch (Exception e) {
			
		}return jugadores;
		
	}
}
